﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MiniX.API.Data;
using MiniX.Models;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Senparc.CO2NET.Extensions;
using MiniX.Utility.Helper;
using MiniX.API.Filters;

namespace MiniX.API.Controllers
{
    /// <summary>
    /// 短信类，定义了CURD相关操作
    /// </summary>
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class SmsController : BaseController<SmsController>
    {
        /// <summary>
        /// SmsController
        /// </summary>
        public SmsController(MiniXApiContext context, IHttpContextAccessor httpContextAccessor) : base(context, httpContextAccessor)
        {

        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="paras">构造短信对象数据</param>
        /// <returns>返回新增的短信</returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("/api/sms")]
        public async Task<IActionResult> Create(LoginParas paras)
        {
            try
            {
                var mobile_phone = paras.mobile;
                log.Information("mobile=" + mobile_phone);
                var item = await _context.mini_codes.OrderByDescending(c => c.created_at).FirstOrDefaultAsync(m => m.mobile_phone!.Contains(mobile_phone!));
                if (item != null)
                {
                    if (item.created_at.AddMinutes(1) > DateTime.Now)
                    {
                        return Json(new { code = 0, msg = "发送太频繁，请稍后发送！" });
                    }
                }

                var code = MiniX.Utility.Helper.CommonHelper.GenerateRandomNum(6);
                var result = MiniX.Utility.Sms.SMSHelper.SendVerifyCode(mobile_phone!, code); // SMS渠道
                var sign_name = AppSettingsFilter.GetSetting("Setting:SignName");
                // var template_code = "SMS_465370967";
                // var result = MiniX.Utility.Sms.AliyunSmsHelper.SendVerifyCode(sign_name, template_code, mobile_phone!, code); // 阿里云渠道

                // 添加短信日志
                try
                {
                    var sms = new Sms()
                    {
                        mobile_phone = mobile_phone,
                        sms_content = "您的验证码为：" + code + "，请勿泄露于他人！【" + sign_name + "】",
                        result_content = result,
                        created_at = DateTime.Now
                    };
                    _context.mini_sms.Add(sms);
                    _context.SaveChanges();
                }
                catch (Exception ex)
                {
                    log.Fatal(ex, " -> 添加短信日志");
                }

                // 添加验证码记录
                try
                {
                    var codes = new Codes()
                    {
                        country_code = "+86",
                        mobile_phone = mobile_phone,
                        code_num = code,
                        code_from = paras.platform,
                        due_minute = 10,
                        created_at = DateTime.Now
                    };
                    _context.mini_codes.Add(codes);
                    _context.SaveChanges();
                }
                catch (Exception ex)
                {
                    log.Fatal(ex, " -> 添加验证码记录");
                }

                return Json(new { code = 0, msg = "验证码发送成功，请注意查收！" });
            }
            catch (Exception ex)
            {
                log.Fatal(ex, " -> Create");
                return Json(new { code = 1, errcode = (int)ENUMHelper.ExceptionType.Create, errmsg = ex.Message });
            }
        }
    }
}
